import React, { useState } from 'react';
import { Upload, Button, message, Progress, Card, Typography, Space } from 'antd';
import { 
  UploadOutlined, 
  FileWordOutlined, 
  FilePptOutlined, 
  FilePdfOutlined,
  EyeOutlined,
  DeleteOutlined,
  FileExcelOutlined
} from '@ant-design/icons';
import mammoth from 'mammoth';

import { FileViewerTrigger } from '../FileViewer/FileViewer';
import './FileUpload.scss';

const { Text } = Typography;

const FileUpload = ({ onFileUploaded, onFileConverted, maxFiles = 5 }) => {
  const [fileList, setFileList] = useState([]);
  const [convertedFiles, setConvertedFiles] = useState([]);
  const [converting, setConverting] = useState(false);

  // 支持的文件类型
  const supportedTypes = {
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'word',
    'application/msword': 'word',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'ppt',
    'application/vnd.ms-powerpoint': 'ppt',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'excel',
    'application/vnd.ms-excel': 'excel',
    'application/pdf': 'pdf',
    'text/plain': 'txt',
    'text/csv': 'csv'
  };

  // 获取文件图标
  const getFileIcon = (fileType) => {
    switch (fileType) {
      case 'word':
        return <FileWordOutlined style={{ fontSize: 24, color: '#1890ff' }} />;
      case 'ppt':
        return <FilePptOutlined style={{ fontSize: 24, color: '#fa8c16' }} />;
      case 'pdf':
        return <FilePdfOutlined style={{ fontSize: 24, color: '#f5222d' }} />;
      case 'excel':
        return <FileExcelOutlined style={{ fontSize: 24, color: '#52c41a' }} />;
      case 'txt':
      case 'csv':
        return <FileWordOutlined style={{ fontSize: 24, color: '#666' }} />;
      default:
        return <UploadOutlined style={{ fontSize: 24 }} />;
    }
  };

  // Word文档处理（仅用于富文本编辑器插入）
  const convertWordToHtml = async (file) => {
    try {
      const arrayBuffer = await file.arrayBuffer();
      const result = await mammoth.convertToHtml({ arrayBuffer });
      return {
        html: result.value,
        messages: result.messages
      };
    } catch (error) {
      throw new Error(`Word转换失败: ${error.message}`);
    }
  };

  // 文件处理
  const handleFileUpload = async (file) => {
    const fileType = supportedTypes[file.type];
    if (!fileType) {
      throw new Error('不支持的文件类型');
    }

    setConverting(true);
    
    try {
      // 创建文件URL用于预览
      const fileUrl = URL.createObjectURL(file);
      
      let result = null;
      
      // 只有Word文档才转换为HTML用于富文本编辑器插入
      if (fileType === 'word') {
        result = await convertWordToHtml(file);
      }

      const uploadedFile = {
        id: Date.now(),
        name: file.name,
        type: fileType,
        size: file.size,
        fileUrl: fileUrl,
        html: result ? result.html : null, // 只有Word文档有HTML内容
        messages: result ? result.messages : [`${file.name} 已上传，支持在线预览`],
        uploadedAt: new Date().toISOString()
      };

      setConvertedFiles(prev => [...prev, uploadedFile]);
      onFileConverted && onFileConverted(uploadedFile);
      
      message.success(`${file.name} 上传成功`);
      
    } catch (error) {
      message.error(error.message);
      console.error('文件上传错误:', error);
    } finally {
      setConverting(false);
    }
  };

  // 上传配置
  const uploadProps = {
    multiple: true,
    maxCount: maxFiles,
    beforeUpload: (file) => {
      // 检查文件类型
      if (!supportedTypes[file.type]) {
        message.error(`不支持的文件类型: ${file.name}`);
        return false;
      }

      // 检查文件大小 (限制50MB)
      const maxSize = 50 * 1024 * 1024;
      if (file.size > maxSize) {
        message.error(`文件过大: ${file.name}，请选择小于50MB的文件`);
        return false;
      }

      // 开始上传处理
      handleFileUpload(file);
      return false; // 阻止自动上传
    },
    onChange: (info) => {
      setFileList(info.fileList);
    },
    onRemove: (file) => {
      setFileList(prev => prev.filter(item => item.uid !== file.uid));
    }
  };

  // 预览转换结果
  const previewConvertedFile = (file) => {
    const newWindow = window.open('', '_blank');
    newWindow.document.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>${file.name} - 预览</title>
          <meta charset="utf-8">
          <style>
            body { 
              font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
              line-height: 1.6;
              max-width: 800px;
              margin: 0 auto;
              padding: 20px;
            }
            .pdf-placeholder, .ppt-placeholder {
              border: 2px dashed #d9d9d9;
              padding: 40px;
              text-align: center;
              border-radius: 8px;
              background: #fafafa;
            }
          </style>
        </head>
        <body>
          ${file.html}
        </body>
      </html>
    `);
    newWindow.document.close();
  };

  // 删除转换文件
  const removeConvertedFile = (fileId) => {
    setConvertedFiles(prev => prev.filter(file => file.id !== fileId));
    message.success('文件已删除');
  };

  return (
    <div className="file-upload-container">
      <Card title="文档上传与预览" className="upload-card">
        <Space direction="vertical" style={{ width: '100%' }}>
          <div className="upload-area">
            <Upload.Dragger {...uploadProps} className="upload-dragger">
              <p className="ant-upload-drag-icon">
                <UploadOutlined />
              </p>
              <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
              <p className="ant-upload-hint">
                支持 Word (.docx, .doc)、PowerPoint (.pptx, .ppt)、PDF (.pdf)、Excel (.xlsx, .xls)、文本 (.txt, .csv) 格式
                <br />
                所有文件支持在线预览，Word文档可插入富文本编辑器
                <br />
                单个文件大小不超过 50MB，最多上传 {maxFiles} 个文件
              </p>
            </Upload.Dragger>
          </div>

          {converting && (
            <div className="converting-status">
              <Progress percent={100} status="active" showInfo={false} />
              <Text type="secondary">正在处理文档...</Text>
            </div>
          )}
        </Space>
      </Card>

      {/* 转换结果列表 */}
      {convertedFiles.length > 0 && (
        <Card title="上传文件" className="converted-files-card">
          <Space direction="vertical" style={{ width: '100%' }}>
            {convertedFiles.map(file => (
              <Card 
                key={file.id}
                size="small"
                className="converted-file-item"
                actions={[
                  <FileViewerTrigger
                    key="preview"
                    fileUrl={file.fileUrl}
                    fileName={file.name}
                    buttonProps={{
                      type: "link",
                      icon: <EyeOutlined />,
                      size: "small"
                    }}
                  >
                    预览
                  </FileViewerTrigger>,
                  ...(file.type === 'word' && file.html ? [
                    <Button 
                      key="html-preview"
                      type="link" 
                      icon={<EyeOutlined />}
                      onClick={() => previewConvertedFile(file)}
                      size="small"
                    >
                      插入编辑器
                    </Button>
                  ] : []),
                  <Button 
                    key="delete"
                    type="link" 
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => removeConvertedFile(file.id)}
                    size="small"
                  >
                    删除
                  </Button>
                ]}
              >
                <Card.Meta
                  avatar={getFileIcon(file.type)}
                  title={file.name}
                  description={
                    <Space direction="vertical" size="small">
                      <Text type="secondary">
                        大小: {(file.size / 1024 / 1024).toFixed(2)} MB
                      </Text>
                      <Text type="secondary">
                        上传时间: {new Date(file.uploadedAt || file.convertedAt).toLocaleString()}
                      </Text>
                      {file.messages.length > 0 && (
                        <Text type="warning" style={{ fontSize: 12 }}>
                          {file.messages.join(', ')}
                        </Text>
                      )}
                    </Space>
                  }
                />
              </Card>
            ))}
          </Space>
        </Card>
      )}
    </div>
  );
};

export default FileUpload;